<?php

require_once SYS_PATH.'sys/class/extend/saetv2.ex.class.php';

/**
 * sina微博登录  http://open.weibo.com/申请appid, appkey, 并注册callback地址
 * 
 * Flan@2012-11-20
*/
class opensinaAction extends openapiAction {
	
	private $m_aError = array();
	
	
	private $m_pSina;
	
	function __construct(){
        parent::__construct();
		$this->m_nOpenType = 1;
		$this->m_nOpenTypeName = $this->m_aOpenType[$this->m_nOpenType - 1];
		
		// WB_AKEY
		$this->m_appid = 1224588771;
		// WB_SKEY
		$this->m_appkey = '8990212012aa2bb147c9585efab4cf2d';
		// WB_CALLBACK_URL
		$this->m_callback = 'http://member.che1an.com/open/opensina/callback';
		
		
		$this->m_pSina = new SaeTOAuthV2($this->m_appid ,$this->m_appkey);
	}
	
	function loginto(){
// 		cookie::set('open['.$this->m_nOpenTypeName.']', '', -3600*24*5);
		
		$login_url = $this->m_pSina->getAuthorizeURL($this->m_callback);
		header("Location:$login_url");
	}
	
	function callback(){
		
		$aToken = $this->getToken();
		$sToken = $aToken['access_token'];
		$sOpenId = $aToken['uid'];

// 		[access_token] => 2.00biUM8CnTPs1B77d49383f4Fr1neC
// 		[remind_in] => 640544
// 		[expires_in] => 640544
// 		[uid] => 2234204757

		$this->m_sToken = $sToken;
		$this->m_sOpenId = $sOpenId;

		// echo '$sToken:'.$sToken;
		// echo '<br />';
		// echo '$sOpenId:'.$sOpenId;
		// echo '<br />';
		
		$this->setCookie(array('token' => $sToken));
		
 		$aUserInfo = $this->getUserInfo();
		
 		//print_r($aUserInfo);
        $this->m_sNickname = $aUserInfo['screen_name'];
		//echo $this->m_sNickname;
 		$this->loginFlow();
		
	}
	
	/**
	 * 取得access_token
	 *
	 * @access public
	 * @return int openid
	 */
	private function getToken(){
		if (isset($_REQUEST['code'])) {
			$keys = array();
			$keys['code'] = $_REQUEST['code'];
			$keys['redirect_uri'] = $this->m_callback;
			try {
				$token = $this->m_pSina->getAccessToken( 'code', $keys ) ;
			} catch (OAuthException $e) {
				// null
			}
		}

		return $token;
	}
	
	/**
	 * 取得用户基础信息
	 * 
	 * @access public 
	 * @return return_type
	 */
	private function getUserInfo(){
		$c = new SaeTClientV2( $this->m_appid , $this->m_appkey , $this->m_sToken );
		$ms  = $c->home_timeline(); // done
		$uid_get = $c->get_uid();
		$uid = $uid_get['uid'];
		$user_message = $c->show_user_by_id( $uid);//根据ID获取用户等基本信息
		
		return $user_message;
	}
	
}
